import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getShipment, 
  getShipmentRoute, 
  getShipmentHistoryTrack, 
  getShipmentCurrentLocation,
  testGpsDevice 
} from '@/api/shipment'
import { addressService } from '@/services/addressService'

export function useRouteData(shipmentId) {
  const loading = ref(false)
  const locationLoading = ref(false)
  const routePoints = ref([])
  const shipmentInfo = ref({})
  const currentLocation = ref(null)
  const isOperating = ref(false)

  // 查询表单
  const queryForm = ref({
    startTime: '',
    endTime: ''
  })

  // 初始化默认时间（最近24小时）
  const initDefaultTime = () => {
    const now = new Date()
    const yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1000)
    
    queryForm.value.endTime = now.toISOString().slice(0, 19).replace('T', ' ')
    queryForm.value.startTime = yesterday.toISOString().slice(0, 19).replace('T', ' ')
  }

  // 获取货物信息
  const fetchShipmentInfo = async () => {
    try {
      const res = await getShipment(shipmentId.value)
      // 统一响应格式处理
      if (res.code === 200 && res.data) {
        shipmentInfo.value = res.data || {}
      } else {
        // 兼容直接返回数据的格式
        shipmentInfo.value = res.data || res || {}
      }
    } catch (error) {
      console.error('获取货物信息失败:', error)
      ElMessage.error('获取货物信息失败')
    }
  }

  // 获取存储的路线数据 - 修改为自动获取历史数据
  const fetchRouteData = async () => {
    if (isOperating.value) {
      return
    }
    
    loading.value = true
    isOperating.value = true
    
    try {
      console.log('自动获取路线数据...')
      const res = await getShipmentRoute(shipmentId.value)
      console.log('路线API响应:', res)
      
      // 统一响应格式处理
      if (res.code === 200 && res.data) {
        const points = res.data.points || []
        
        if (validateRoutePoints(points)) {
          routePoints.value = points
          const totalPoints = res.data.total_points || points.length
          ElMessage.success(`自动加载了 ${totalPoints} 个轨迹点`)
          
          console.log('自动加载路线数据成功:', {
            shipment_id: res.data.shipment_id,
            total_points: totalPoints,
            start_time: res.data.start_time,
            end_time: res.data.end_time,
            status: res.data.status
          })
        } else {
          ElMessage.info('当前没有可用的轨迹数据')
          routePoints.value = []
        }
      } else if (res.points) {
        // 兼容旧格式
        const points = res.points || []
        
        if (validateRoutePoints(points)) {
          routePoints.value = points
          ElMessage.success(`自动加载了 ${points.length} 个轨迹点`)
        } else {
          ElMessage.info('当前没有可用的轨迹数据')
          routePoints.value = []
        }
      } else {
        console.warn('路线响应格式:', res)
        ElMessage.info('当前没有可用的轨迹数据')
        routePoints.value = []
      }
    } catch (error) {
      console.error('获取路线数据失败:', error)
      ElMessage.error('获取路线数据失败')
      routePoints.value = []
    } finally {
      loading.value = false
      setTimeout(() => {
        isOperating.value = false
      }, 1000)
    }
  }

  // 数据验证工具函数
  const validateRoutePoints = (points) => {
    if (!Array.isArray(points)) {
      console.warn('轨迹点数据不是数组格式:', points)
      return false
    }
    
    const validPoints = points.filter(point => 
      point && 
      typeof point.lat === 'number' && 
      typeof point.lng === 'number' &&
      !isNaN(point.lat) && 
      !isNaN(point.lng) &&
      point.lat !== 0 && 
      point.lng !== 0
    )
    
    console.log(`轨迹点验证结果: 总计 ${points.length} 个点，有效点 ${validPoints.length} 个`)
    
    if (validPoints.length > 0) {
      console.log('样本数据:', {
        firstPoint: validPoints[0],
        lastPoint: validPoints[validPoints.length - 1],
        dataStructure: Object.keys(validPoints[0])
      })
    }
    
    return validPoints.length > 0
  }

  // 从GPS API获取历史轨迹数据
  const fetchGpsTrackData = async () => {
    if (isOperating.value) {
      ElMessage.warning('正在处理中，请稍候...')
      return
    }
    loading.value = true
    isOperating.value = true
    try {
      console.log('开始获取路线数据...')
      // 由于history-track API已移除，使用route API代替
      const res = await getShipmentRoute(shipmentId.value)
      
      console.log('路线API响应:', res)
      
      // 统一响应格式处理
      if (res.code === 200 && res.data) {
        const points = res.data.points || []
        
        if (validateRoutePoints(points)) {
          routePoints.value = points
          const totalPoints = res.data.total_points || points.length
          ElMessage.success(`成功获取 ${totalPoints} 个轨迹点`)
          
          console.log('轨迹数据解析成功:', {
            shipment_id: res.data.shipment_id,
            total_points: totalPoints,
            start_time: res.data.start_time,
            end_time: res.data.end_time,
            actual_points: points.length
          })
        } else {
          ElMessage.warning('获取的轨迹数据格式异常或为空')
          routePoints.value = []
        }
      } else if (res.points) {
        // 兼容旧格式
        const points = res.points || []
        
        if (validateRoutePoints(points)) {
          routePoints.value = points
          ElMessage.success(`成功获取 ${res.total_points || points.length} 个轨迹点`)
        } else {
          ElMessage.warning('获取的轨迹数据格式异常或为空')
          routePoints.value = []
        }
      } else {
        console.warn('未识别的响应格式:', res)
        ElMessage.warning('服务器返回的数据格式异常')
        routePoints.value = []
      }
    } catch (error) {
      console.error('获取轨迹数据失败:', error)
      ElMessage.error(`获取轨迹数据失败: ${error.message || '未知错误'}`)
      routePoints.value = []
    } finally {
      loading.value = false
      // 延迟重置操作状态，确保地图操作完成
      setTimeout(() => {
        isOperating.value = false
      }, 2000)
    }
  }
  // 刷新数据
  const handleRefresh = async () => {
    if (isOperating.value) {
      ElMessage.warning('正在处理中，请稍候...')
      return
    }
    try {
      await fetchShipmentInfo()
      await fetchGpsTrackData()
    } finally {
      setTimeout(() => {
        isOperating.value = false
      }, 2000)
    }
  }

  return {
    // 响应式数据
    loading,
    locationLoading,
    routePoints,
    shipmentInfo,
    currentLocation,
    isOperating,
    queryForm,
    
    // 方法
    initDefaultTime,
    fetchShipmentInfo,
    fetchRouteData,
    fetchGpsTrackData,
    handleRefresh
  }
}